import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Route, Redirect } from 'react-router'
import { global as userDuck } from 'ducks'

const createRedirect = ({ location }) => ({
  pathname: '/auth',
  state: {
    returnURL: location.pathname,
  },
})

const createRedirectHome = ({ location }) => ({
  pathname: '/fetchUser',
  state: {
    returnURL: location.pathname,
  },
})

const PrivateRoute = ({
  component: Component, isSignedIn, isAuthed, render, ...rest
}) => {
  let renderFunction
  if (isAuthed && isSignedIn) {
    renderFunction = render || (props => <Component {...props} {...rest} />)
  } else if (isAuthed && !isSignedIn) {
    renderFunction = props => <Redirect to={createRedirectHome(props)} />
  } else {
    renderFunction = props => <Redirect to={createRedirect(props)} />
  }
  return <Route {...rest} render={renderFunction} />
}

PrivateRoute.propTypes = {
  component: PropTypes.func.isRequired,
  isSignedIn: PropTypes.bool.isRequired,
}

const mapStateToProps = state => ({
  isSignedIn: userDuck.selectors.isSignedIn(state),
  isAuthed: userDuck.selectors.isAuthed(state),
})

export default connect(mapStateToProps)(PrivateRoute)
